﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Autodesk.AutoCAD.Windows;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.ApplicationServices;
using ACADApplication = Autodesk.AutoCAD.ApplicationServices.Application;
using ACADDatabase = Autodesk.AutoCAD.DatabaseServices.Database;
using ACADDocument = Autodesk.AutoCAD.ApplicationServices.Document;

namespace YNCNumberSys
{
    public class ZJGetXrecord
    {
        #region
        /// <summary>
        /// 数据字典.
        /// </summary>
        DBDictionary _dct_DBDictionary;
        /// <summary>
        /// 扩展记录名.
        /// </summary>
        string _str_XrecordName;
        /// <summary>
        /// 事务,为空表示操作当前图纸空间.
        /// </summary>
        private Transaction _trs_Transaction;
        /// <summary>
        /// 图纸文档WorkingDatabase,为空表示当前的图纸空间.
        /// </summary>
        private ACADDatabase _wdb_DataBase;
        /// <summary>
        /// 该值如果为True,则(1)_trs_Transaction,_wdb_DataBase均为当前图纸空间;(2)事务提交在该类内完成.
        /// </summary>
        private bool _b_TransactionIsUsed;
        #endregion
        public ZJGetXrecord(ACADDatabase wdb_DataBase, Transaction trs_Transaction,
            DBDictionary dct_DBDictionary, string str_XrecordName)
        {
            _wdb_DataBase = wdb_DataBase;
            _trs_Transaction = trs_Transaction;
            _dct_DBDictionary = dct_DBDictionary;
            _str_XrecordName = str_XrecordName;
            _b_TransactionIsUsed = true;
        }

        public ZJGetXrecord(DBDictionary dct_DBDictionary, string str_XrecordName)
        {
            _wdb_DataBase = HostApplicationServices.WorkingDatabase;
            _trs_Transaction = null;
            _dct_DBDictionary = dct_DBDictionary;
            _str_XrecordName = str_XrecordName;
            _b_TransactionIsUsed = false;
        }
        public ResultBuffer Do()
        {
            Xrecord rec = null;
            if (_dct_DBDictionary.Contains(_str_XrecordName))
            {
                if (_b_TransactionIsUsed)
                {
                    rec = (Xrecord)_trs_Transaction.GetObject(_dct_DBDictionary.GetAt(_str_XrecordName), OpenMode.ForRead);
                }
                else
                {
                    using (_trs_Transaction = _wdb_DataBase.TransactionManager.StartTransaction())
                    {
                        rec = (Xrecord)_trs_Transaction.GetObject(_dct_DBDictionary.GetAt(_str_XrecordName), OpenMode.ForRead);
                        _trs_Transaction.Commit();
                        _trs_Transaction.Dispose();
                    }
                }
            }
            if (null != rec)
                return rec.Data;
            else
                return null;
        }
    }
}
